package com.aynu.likou;

/**
 * @author mj
 * @create 2021-04-08 18:33
 * @describe: 编写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串 ""。
 */
public class QianZhui {
    public static void main(String[] args) {
        String[] strs = new String[]{"flower", "flow", "flight"};
        System.out.println(System.currentTimeMillis());
        System.out.println(longestCommonPrefixOptimization(strs));
        System.out.println(System.currentTimeMillis());
    }

    //寻找最大前缀
    public static String longestCommonPrefix(String[] strs) {
        if (strs.length <= 0) {
            return "";
        }
        for (int i = strs[0].length(); i >= 0; i--) {
            //以第一个数为标准
            String substring = strs[0].substring(0, i);
            int num = 0;
            for (String str : strs) {
                //判断截取出的字符串是否大于等于遍历的字符串
                if (str.length() >= substring.length()) {
                    //判断标准字符是否达当前循环的字符串截取的字符串
                    if (str.substring(0, i).equals(substring)) {
                        num++;
                    }
                }
            }
            if (num == strs.length) {
                return substring;
            }
        }
        return "";
    }

    //力扣评论优化版
    public static String longestCommonPrefixOptimization(String[] strs) {
        if (strs.length <= 0) {
            return "";
        }
        String str = strs[0];
        for (String s : strs) {
            while (!s.startsWith(str)){
                if (s.length()==0){
                    return "";
                }
                str = str.substring(0,str.length() - 1);
            }
        }
        return str;
    }
}
